package rpc.frame.server.registry.zk;

import org.I0Itec.zkclient.ZkClient;
import org.springframework.stereotype.Component;
import rpc.frame.server.config.RpcServerConfiguration;

import javax.annotation.Resource;

/**
 * 操作zk的工具类
 */
@Component
public class ServerZk {

    @Resource
    private RpcServerConfiguration rpcServerConfiguration;
    @Resource
    private ZkClient zkClient;

    /**
     * 创建根节点 持久节点
     */
    public void createRootNode(){
        boolean exists=zkClient.exists(rpcServerConfiguration.getRoot());
        if(!exists){
            zkClient.createPersistent(rpcServerConfiguration.getRoot());
        }
    }

    /**
     * 创建其他节点
     */
    public void createPersistentNode(String path){
        String pathName=rpcServerConfiguration.getRoot()+"/"+path;
        boolean exists = zkClient.exists(pathName);
        if(!exists){
            zkClient.createPersistent(pathName);
        }
    }

    /**
     * 创建节点
     */
    public void createNode(String path){
        String pathName=rpcServerConfiguration.getRoot()+"/"+path;
        boolean exists = zkClient.exists(pathName);
        if(!exists){
            zkClient.createEphemeral(pathName);
        }
    }
}
